<script lang="ts" setup>
import { ref, onMounted, onUnmounted } from "vue";
import SeparatePageLayout from "@/layouts/SeparatePageLayout.vue";
import { api } from "@/utils/api";

interface Message {
  id: number;
  name: string;
  date: string;
  content: string;
  replyTo?: number | null;
  replyToUserName?: string;
  replies: Message[];
  showReplies: boolean;
}

interface MessageResponse {
  createBy: string;
  updateBy: string;
  createTime: string;
  updateTime: string;
  id: number;
  name: string;
  phoneNumber: string;
  mailbox: string;
  msg: string;
  isState: boolean;
  replyTo?: number | null;
}

// 留言列表数据
const messages = ref<Message[]>([]);

// 用于存储所有消息的映射
const messageMap: Map<number, Message> = new Map();

// 分页控制
const page = ref(0);
const size = 10; // 每页留言条数
const isLastPage = ref(false); // 用于标记是否已加载到最后一页

// 表单数据
const formData = ref({
  name: "",
  phoneNumber: "",
  mailbox: "",
  msg: "",
  replyTo: null as number | null,
});

// 表单提交函数
const submitForm = async () => {
  if (!formData.value.msg) {
    alert("留言内容为必填项");
    return;
  }

  // 设置 replyTo 字段为 null，表示不支持回复功能
  formData.value.replyTo = null;

  // 提交留言到后端
  try {
    const response = await api.postMessage(formData.value);
    if (response.code === 1) {
      alert("留言已提交！");
      formData.value = { name: "", phoneNumber: "", mailbox: "", msg: "", replyTo: null }; // 清空表单
      page.value = 0; // 重置分页
      messages.value = []; // 清空当前留言列表
      isLastPage.value = false; // 重置是否为最后一页的标志
      messageMap.clear(); // 清空消息映射
      await loadMessages(); // 提交成功后重新加载留言列表
    } else {
      alert("提交失败：" + response.msg);
    }
  } catch (error) {
    console.error("留言提交失败", error);
  }
};

// 加载留言列表
const loadMessages = async () => {
  if (isLastPage.value) return; // 若已到最后一页则不再请求

  try {
    const response = await api.getMessage(page.value, size);
    if (response.code === 1) {
      const allMessages: Message[] = response.data.content.map((item: MessageResponse) => ({
        id: item.id,
        name: item.replyTo?"育杰奖学金":item.name || "匿名用户",
        date: item.createTime,
        content: item.msg,
        replyTo: item.replyTo || null,
        replyToUserName: "",
        replies: [],
        showReplies: false,
      }));

      // 将所有消息添加到映射中
      allMessages.forEach((msg) => {
        messageMap.set(msg.id, msg);
      });

      // 构建消息的层次结构
      allMessages.forEach((msg) => {
        if (msg.replyTo) {
          const parentMsg = messageMap.get(msg.replyTo);
          if (parentMsg) {
            msg.replyToUserName = parentMsg.name;
            parentMsg.replies.push(msg);
          }
        }
      });

      // 获取顶级留言（replyTo 为 null）
      const topLevelMessages = allMessages.filter((msg) => !msg.replyTo);

      messages.value = [...messages.value, ...topLevelMessages]; // 追加顶级留言
      page.value += 1; // 下一页
      isLastPage.value = response.data.last; // 若已是最后一页，标记为 true
    } else {
      console.error("加载留言失败：" + response.msg);
    }
  } catch (error) {
    console.error("加载留言时出现错误", error);
  }
};

// 切换显示回复
const toggleShowReplies = (message: Message) => {
  message.showReplies = !message.showReplies;
};

// 监听滚动事件，检测是否到底部
const handleScroll = () => {
  const scrollTop = document.documentElement.scrollTop || document.body.scrollTop;
  const windowHeight = window.innerHeight;
  const scrollHeight = document.documentElement.scrollHeight || document.body.scrollHeight;

  if (scrollTop + windowHeight >= scrollHeight - 10) {
    // 滚动到底部时加载更多留言
    loadMessages();
  }
};

// 页面加载时获取留言并添加滚动监听
onMounted(() => {
  loadMessages();
  window.addEventListener("scroll", handleScroll);
});

// 组件卸载时移除滚动监听
onUnmounted(() => {
  window.removeEventListener("scroll", handleScroll);
});
</script>

<template>
  <separate-page-layout>
    <div class="w-web mx-auto flex gap-16 p-4">
      <!-- 留言展示列表 -->
      <div class="w-3/4 space-y-4">
        <div
            v-for="(message, index) in messages"
            :key="index"
            class="border-b pb-4 p-2"
        >
          <!-- 消息头部 -->
          <div class="flex justify-between text-sm text-gray-500 mb-2">
            <div class="font-bold">{{ message.name }}</div>
            <div>{{ message.date }}</div>
          </div>

          <!-- 如果是回复消息，显示回复信息 -->
          <div v-if="message.replyTo" class="text-sm text-gray-500 mb-1">
            <strong>回复</strong> {{ message.replyToUserName }}
          </div>

          <!-- 消息内容 -->
          <p class="text-gray-700">{{ message.content }}</p>

          <!-- 展示回复按钮 -->
          <div class="flex justify-end space-x-2 mt-2">
            <button
                v-if="message.replies && message.replies.length > 0"
                class="text-blue-500 hover:underline"
                @click="toggleShowReplies(message)"
            >
              {{ message.showReplies ? '隐藏回复' : '展示回复' }}
            </button>
          </div>

          <!-- 回复列表 -->
          <div v-if="message.showReplies" class="ml-4 mt-2">
            <div
                v-for="reply in message.replies"
                :key="reply.id"
                class="border-b pb-4 p-2"
            >
              <!-- 回复消息头部 -->
              <div class="flex justify-between text-sm text-gray-500 mb-2">
                <div class="font-bold">{{ reply.name }}</div>
                <div>{{ reply.date }}</div>
              </div>

              <!-- 如果是回复消息，显示回复信息 -->
              <div v-if="reply.replyTo" class="text-sm text-gray-500 mb-1">
                <strong>回复</strong> {{ reply.replyToUserName }}
              </div>

              <!-- 回复消息内容 -->
              <p class="text-gray-700">{{ reply.content }}</p>
            </div>
          </div>
        </div>
      </div>

      <!-- 留言提交表单 -->
      <div class="w-1/4 space-y-4">
        <h2 class="text-xl font-semibold">提交留言</h2>
        <form class="space-y-3" @submit.prevent="submitForm">
          <div class="flex flex-nowrap">
            <label class="flex items-center whitespace-nowrap">姓名：</label>
            <input
                v-model="formData.name"
                class="w-full border-b focus:outline-none focus:border-blue-500 p-2"
                type="text"
            />
          </div>
          <div class="flex flex-nowrap">
            <label class="flex items-center whitespace-nowrap">电话：</label>
            <input
                v-model="formData.phoneNumber"
                class="w-full border-b focus:outline-none focus:border-blue-500 p-2"
                type="text"
            />
          </div>
          <div class="flex flex-nowrap">
            <label class="flex items-center whitespace-nowrap">邮箱：</label>
            <input
                v-model="formData.mailbox"
                class="w-full border-b focus:outline-none focus:border-blue-500 p-2"
                type="email"
            />
          </div>
          <div class="flex flex-wrap">
            <label class="flex whitespace-nowrap mb-2.5">
              <span class="text-red-500 mr-1">*</span>留言内容
            </label>
            <textarea
                v-model="formData.msg"
                class="w-full border focus:outline-none focus:border-blue-500 p-2 resize-y"
                required
                rows="4"
            ></textarea>
          </div>

          <button
              class="w-full bg-blue-500 text-white rounded py-2 font-semibold hover:bg-blue-600 transition-colors"
              type="submit"
          >
            提交留言
          </button>
        </form>
      </div>
    </div>
  </separate-page-layout>
</template>

<style scoped>
</style>